#include <windows.h>
#include <strsafe.h>
#include "Util.h"

// See
//  http://msdn.microsoft.com/en-us/library/ms680582%28VS.85%29.aspx
//
void
OutputLastError(LPTSTR lpszFunction)
{
    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError();

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    if (NULL == lpMsgBuf)
        return;

    // Display the error message and exit the process

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
        (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));

    if (NULL == lpDisplayBuf) {
        LocalFree(lpMsgBuf);
        return;
    }

    StringCchPrintf((LPTSTR)lpDisplayBuf,
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"),
        lpszFunction, dw, lpMsgBuf);
    //MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
    OutputDebugString((LPTSTR)lpDisplayBuf);

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
    //ExitProcess(dw);
}

CMzString
GetResourcePath(const TCHAR* path)
{
    CMzString fullpath = MzGetModuleFileName(MzGetInstanceHandle());
    int lastBackslash = fullpath.FindReverse(TEXT('\\'));

    if (lastBackslash < 0)
        return CMzString();

    CMzString dirpath = fullpath.SubStr(0, lastBackslash + 1);
    return CMzString(dirpath + path);
}

